package com.itdaan.portal.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author www.itdaan.com
 */
public class MD5Util {
    private static Logger logger = LoggerFactory.getLogger(MD5Util.class);

    public static String get32BitMD5(String plainText) {
        return getMd5("32", plainText);
    }

    public static String get16BitMD5(String plainText) {
        return getMd5("16", plainText);
    }
  
    private static String getMd5(String type, String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            if (type.equals("32")) {
                return buf.toString();
            } else if (type.equals("16")) {
                return buf.toString().substring(8, 24);
            }
        } catch (NoSuchAlgorithmException e) {
            logger.error("MD5加密出现异常", e);
        }
        return null;
    }
    
    public static String[] getMd5ToArray(String md5){
    	String[] path = null;
    	if(md5!=null && md5.length()>=4){
    		String[] path2 = {md5.substring(0,2),md5.substring(md5.length()-2,md5.length())};
    		path = path2;
    	}
    	return path;
    }
    
}
